package com.ptszyxx.popose.module.main.mine;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import com.baidu.idl.face.api.manager.FaceConst;
import com.baidu.idl.face.api.manager.FaceInitCallback;
import com.baidu.idl.face.api.manager.FaceServiceCallbck;
import com.baidu.idl.face.api.manager.FaceServiceManager;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.facelive.api.FaceLiveManager;
import com.baidu.idl.facelive.api.entity.FaceLiveConfig;
import com.baidu.idl.facelive.api.entity.FaceLivenessType;
import com.baidu.idl.facelive.api.entity.LivenessValueModel;
import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.face.Config;
import com.ptszyxx.popose.common.face.ConsoleConfig;
import com.ptszyxx.popose.common.face.ConsoleConfigManager;
import com.ptszyxx.popose.common.face.LivenessVsIdcardResult;
import com.ptszyxx.popose.common.face.PoliceCheckResultParser;
import com.ptszyxx.popose.databinding.FragmentMineRealBinding;
import com.ptszyxx.popose.module.main.mine.vm.MineRealVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.utils.YPermissionUtil;
import com.ysg.utils.YToastUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class MineRealFragment extends BaseFragment<FragmentMineRealBinding, MineRealVM> {
    public ConsoleConfig consoleConfig;
    private final String recogType = FaceConst.FACE_RECOGNIZE;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_mine_real;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MineRealVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(MineRealVM.class);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        FaceServiceManager.release();
    }

    @Override
    public void initView() {
        super.initView();
        initFace();
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestAccessToken();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onFaceEvent.observe(this, o -> showPermission());
    }

    private void initFace() {
        FaceServiceManager.getInstance().init(getActivity(),Config.licenseID, Config.licenseFileName, Config.keyName, new FaceInitCallback() {
                    @Override
                    public void onCallback(int resultCode, String resultMsg) {
                        Log.e("resultCode", ""+resultCode);
                        Log.e("resultMsg", ""+resultMsg);
                    }
                });
    }

    private void showPermission(){
        YPermissionUtil.requestFace(getActivity(), new YPermissionUtil.OnPermissionListener() {
            @Override
            public void onSuccess() {
                startFaceRecognize();
            }

            @Override
            public void onError() {
            }
        });
    }

    private void startFaceRecognize() {
        String name = viewModel.name.get();
        String id = viewModel.code.get();
        // 人脸阈值设置
        setFaceQualityConfig();
        // LogicServiceManager入参
        Map<String, Object> params = new HashMap<>();
        // 必须携带access_token
        params.put("access_token", viewModel.access_token);
        // 开放平台控制台配置的方案Id
        params.put("plan_id", consoleConfig.getPlanId());
        // 证件类型，0：大陆 1：港澳 2：外国 3：定居国外中国护照
        params.put("verify_type", 0);
        // recogType为FaceRecognize 需要带姓名、证件号
        params.put("name", name);
        params.put("id_card_number", id);
        /**
         * recogType为FaceRecognize可以携带以下参数
         * quality_control 对应console.config中的onlineImageQuality
         * liveness_control 对应console.onlineLivenessQuality
         */
        params.put("quality_control", consoleConfig.getOnlineImageQuality());
        params.put("liveness_control", consoleConfig.getOnlineLivenessQuality());
        FaceServiceManager.getInstance().startFaceRecognize(getActivity(), params, new FaceServiceCallbck() {
            @Override
            public void onCallback(final int resultCode, final Map<String, Object> resultMap) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        handleResult(resultCode, resultMap);
                    }
                });
            }
        });
    }

    private void setFaceQualityConfig() {
        consoleConfig = ConsoleConfigManager.getInstance(getActivity()).getConfig();
        try {
            FaceLiveConfig faceLiveConfig = new FaceLiveConfig();
            // faceUI默认展示结果页，此处必须设置为false
            faceLiveConfig.setShowResultView(false);
            // 设置模糊度阈值
            faceLiveConfig.setBlurnessValue(consoleConfig.getBlur());
            // 设置最小光照阈值（范围0-255）
            faceLiveConfig.setBrightnessValue(consoleConfig.getIllumination());
            // 设置最大光照阈值（范围0-255）
            faceLiveConfig.setBrightnessMaxValue(consoleConfig.getMaxIllumination());
            // 设置左眼遮挡阈值
            faceLiveConfig.setOcclusionLeftEyeValue(consoleConfig.getLeftEyeOcclu());
            // 设置右眼遮挡阈值
            faceLiveConfig.setOcclusionRightEyeValue(consoleConfig.getRightEyeOcclu());
            // 设置鼻子遮挡阈值
            faceLiveConfig.setOcclusionNoseValue(consoleConfig.getNoseOcclu());
            // 设置嘴巴遮挡阈值
            faceLiveConfig.setOcclusionMouthValue(consoleConfig.getMouthOcclu());
            // 设置左脸颊遮挡阈值
            faceLiveConfig.setOcclusionLeftContourValue(consoleConfig.getLeftCheekOcclu());
            // 设置右脸颊遮挡阈值
            faceLiveConfig.setOcclusionRightContourValue(consoleConfig.getRightCheekOcclu());
            // 设置下巴遮挡阈值
            faceLiveConfig.setOcclusionChinValue(consoleConfig.getChinOcclu());
            // 设置人脸姿态Pitch阈值
            faceLiveConfig.setHeadPitchValue(consoleConfig.getPitch());
            // 设置人脸姿态Yaw阈值
            faceLiveConfig.setHeadYawValue(consoleConfig.getYaw());
            // 设置人脸姿态Roll阈值
            faceLiveConfig.setHeadRollValue(consoleConfig.getRoll());
            // 是否开启录制视频
            faceLiveConfig.setOpenRecord(false);
            // 设置是否显示超时弹框
            faceLiveConfig.setIsShowTimeoutDialog(true);
            // 输出图片类型：0原图、1抠图
            faceLiveConfig.setOutputImageType(FaceEnvironment.VALUE_OUTPUT_IMAGE_TYPE);
            // 是否忽略录制异常（只能忽略采集时间过短，采集后无文件输出的异常）
            faceLiveConfig.setIgnoreRecordError(true);
            // 眨眼张嘴遮挡开关
            faceLiveConfig.setActiveStrict(true);
            // 设置活体类型相关
            setFaceLivenessConfig(faceLiveConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setFaceLivenessConfig(FaceLiveConfig faceLiveConfig) {
        try {
            // 设置活体类型：炫彩活体、动作活体、静默活体
            FaceLivenessType faceLivenessType = null;
            // 配置活体动作集合、动作个数，活体阈值，无活体
            LivenessValueModel livenessValueModel = null;
            if (consoleConfig.getFaceLiveType() == 0) {
                faceLivenessType = FaceLivenessType.COLORLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.actionList.addAll(consoleConfig.getActions());
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 1) {
                faceLivenessType = FaceLivenessType.ACTIONLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.actionList.addAll(consoleConfig.getActions());
                livenessValueModel.actionRandomNumber = consoleConfig.getFaceActionNum();
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 2) {
                faceLivenessType = FaceLivenessType.SILENTLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 3) {
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
            }
            // faceLiveConfig.setFaceLivenessType(faceLivenessType, livenessValueModel);
            faceLiveConfig.setLivenessValueModel(livenessValueModel);
            FaceLiveManager.getInstance().setFaceConfig(faceLiveConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleResult(int resultCode, Map<String, Object> resultMap) {
        if (resultCode == 0) {
            String data = (String) resultMap.get(FaceConst.RESULT_JSON);
            PoliceCheckResultParser parser = new PoliceCheckResultParser();
            LivenessVsIdcardResult result = null;
            try {
                result = parser.parse(data);
                if (result == null) {
                    return;
                }

                if (result.getRiskLevel() == 1 || result.getRiskLevel() == 2) {
                    YToastUtil.showShort("失败");
                    return;
                }

                boolean isPass = false;
                if (FaceConst.FACE_LIVENESS.equals(recogType)) {
                    // 在线活体方案：活体分数
                    isPass = result.getFaceliveness() >= 0.8;
                } else {
                    // 实名认证方案：匹配度
                    isPass = result.getScore() >= consoleConfig.getRiskScore();
                }

                if (isPass) {
                    String json = result.getJsonRes();
                    JSONObject jsonObject = new JSONObject(json);
                    String image = jsonObject.getString("dec_image");
                    viewModel.requestRealSave(image);
                } else {
                    YToastUtil.showShort("失败");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                YToastUtil.showShort("失败");
            }
        } else {
            YToastUtil.showShort(resultCode + ":" + resultMap.get("resultMsg"));
        }
    }
}
